import time

import requests
from urllib.parse import quote


class BaiduApi:
    def __init__(self):
        self.API_KEY = "ud75hHybWCZ6rZgdbX9STdDp"
        self.SECRET_KEY = "UjYuiPzTTT6xbdUSDMmoPP1UwENQKPcF"

    def get_access_token(self):
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {
            "grant_type": "client_credentials",
            "client_id": self.API_KEY,
            "client_secret": self.SECRET_KEY
        }
        retries = 3  # 增加重试次数
        for attempt in range(retries):
            try:
                response = requests.post(url, params=params, timeout=10)  # 设置超时时间
                response.raise_for_status()
                return response.json().get("access_token")
            except requests.exceptions.Timeout:
                print(f"第 {attempt + 1} 次尝试超时，正在重试...")
                time.sleep(2)  # 等待2秒后重试
            except Exception as e:
                print(f"获取access_token失败，错误详情: {str(e)}")
                return None
        print("所有重试均失败，请检查网络或API配置")
        return None

    # 身份证验证
    # baidu_api.py (修改身份证识别方法)
    def idcard(self, picurl):
        access_token = self.get_access_token()
        if not access_token:
            return {"code": 10011, 'msg': "获取 access_token 失败"}  # 统一使用msg字段
        url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token={access_token}"
        payload = f'id_card_side=front&url={quote(picurl)}'
        # payload = f'id_card_side=front&url={picurl}'  # 直接使用已编码的picurl
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}

        try:
            response = requests.post(url, headers=headers, data=payload, timeout=15)
            response.raise_for_status()
            data = response.json()

            # 处理百度官方错误码
            if 'error_code' in data:
                error_msg = data.get('error_msg', '未知错误')
                return {"code": data['error_code'], 'msg': error_msg}  # 使用msg字段

            # 处理识别结果
            if 'words_result' in data:
                name = data['words_result'].get('姓名', {}).get('words', '')
                id_num = data['words_result'].get('公民身份号码', {}).get('words', '')
                if name and id_num:
                    return {"code": 200, "name": name, "id_number": id_num}
                else:
                    return {"code": 10010, 'msg': "关键字段缺失"}
            return {"code": 10010, 'msg': "未识别到有效信息"}

        except requests.RequestException as e:
            return {"code": 10012, 'msg': f"网络请求失败: {str(e)}"}
        except ValueError as e:
            return {"code": 10013, 'msg': f"响应解析失败: {str(e)}"}


    # 文字识别
    def fontmessage(self, picurl):
        access_token = self.get_access_token()
        if not access_token:
            return {"code": 10011, 'mes': "获取 access_token 失败"}
        url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token={access_token}"
        payload = f'url={quote(picurl)}&detect_direction=false&paragraph=false&probability=false'
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
        try:
            response = requests.post(url, headers=headers, data=payload)
            response.raise_for_status()
            data = response.json()
            words = [result.get('words') for result in data.get('words_result', [])]
            return {"words": words}
        except requests.RequestException as e:
            print(f"文字识别请求出错: {e}")
            return {"code": 10012, 'mes': f"请求出错: {e}"}
        except ValueError as e:
            print(f"解析文字识别响应时发生 JSON 解析错误: {e}")
            return {"code": 10013, 'mes': f"JSON 解析错误: {e}"}


bdapi = BaiduApi()
# url = quote("http://shfc1pnzg.hb-bkt.clouddn.com/1.png")
# data = bdapi.fontmessage(url)
# print(data)


# 作废
# class BaiduApi:
#     def __init__(self):
#         # self.API_KEY = "ud75hHybWCZ6rZgdbX9STdDp"
#         self.API_KEY = "ud75hHybWCZ6rZgdbX9STdDp"
#         # self.SECRET_KEY = "UjYuiPzTTT6xbdUSDMmoPP1UwENQKPcF"
#         self.SECRET_KEY = "UjYuiPzTTT6xbdUSDMmoPP1UwENQKPcF"
#         self.access_token = self._get_access_token()
#
#     def _get_access_token(self):
#         url = "https://aip.baidubce.com/oauth/2.0/token"
#         params = {
#             "grant_type": "client_credentials",
#             "client_id": self.API_KEY,
#             "client_secret": self.SECRET_KEY
#         }
#         try:
#             response = requests.post(url, params=params)
#             return response.json().get("access_token")
#         except Exception as e:
#             print("获取百度Token失败:", e)
#             return None
#
#     def idcard(self, image_url, side="front"):
#         if not self.access_token:
#             return {"code": 401, "msg": "百度认证失败"}
#         url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token={self.access_token}"
#         payload = {
#             "id_card_side": side,
#             "url": image_url,
#             "detect_risk": "false"
#         }
#         try:
#             response = requests.post(url, data=payload, headers={'Content-Type': 'application/x-www-form-urlencoded'})
#             data = response.json()
#             return data
#         except Exception as e:
#             return {"code": 500, "msg": str(e)}
#
#     def general_ocr(self, image_url):
#         if not self.access_token:
#             return {"code": 401, "msg": "百度认证失败"}
#         url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token={self.access_token}"
#         payload = {"url": image_url}
#         try:
#             response = requests.post(url, data=payload, headers={'Content-Type': 'application/x-www-form-urlencoded'})
#             return response.json()
#         except Exception as e:
#             return {"code": 500, "msg": str(e)}